''' Common methods to work with Liverbird.ru data '''

if __name__ == '__main__':
    pass

import string


class Path():
    def __init__(self, local):
        if local:
            dest_folder = 'data/'
        else:
            dest_folder = '/var/www/liverbird.ru/htdocs/sites/default/files/tables/'

        self.short_table    = dest_folder + 'table_short.html'
        self.full_pl_table  = dest_folder + 'table.html'
        self.full_cl_table  = dest_folder + 'table_cl.html'
        self.archive_path   = dest_folder + 'archive/'
        self.bbc_cl_table_source = 'http://www.bbc.com/sport/football/champions-league/table'

class Download_Games():
    def __init__ (self, base_url, id_range):
        self.range = id_range # range(8037,9319)
        self.base_url =  base_url #'http://www.lfchistory.net/SeasonArchive/Game/' #'http://www.lfchistory.net/SeasonArchive/FriendlyGame/'
    
    def create_files(self, path, code_page = 'utf-8'):
        import urllib.request
        
        for id in self.range:
            in_path = self.base_url+ str(id)
            out_path = '{0}/game_{1}.txt'.format(path, id)
            print (id, in_path, out_path)
            
            try:
                data = urllib.request.urlopen(in_path).read()
            except:
                print ("no game ")
                continue
            
            with open(out_path, mode='w', encoding=code_page) as out_file:
                out_file.write(data.decode(code_page))



class Download_Games_old():
    def __init__ (self, id_range):
        self.range = id_range # range(8037,9319)
        self.base_url =  'http://www.lfchistory.net/SeasonArchive/Game/' #'http://www.lfchistory.net/SeasonArchive/FriendlyGame/'
    
    def create_files(self, path):
        import urllib.request
        
        for id in self.range:
            in_path = self.base_url+ str(id)
            out_path = '{0}/game_{1}.txt'.format(path, id)
            print (id, in_path, out_path)
            
            try:
                data = urllib.request.urlopen(in_path).read()
            except:
                print ("no game ")
                continue
            
            with open(out_path, mode='w', encoding='utf-8') as out_file:
                out_file.write(data.decode('utf-8'))


def import_sql(source, fields, debug = False):
    with open(source, mode = 'r', encoding = 'utf-8') as source_file:
        '''  find the actual data dump'''
        data = source_file.read()
        start = data.find('VALUES (') + len('VALUES (')
        end = data.find(');\n')
        
        assert start > 0 and end > 0, 'Wrong format of dump file'
        
        array = []
        for item in data[start:end].split('),('):
            set = item.split(',')
            
            record = []
            for field in fields:
                assert field < len(set), 'Element not found, index error'
                
                element = set[field]
                
                ''' strip quotes and slashed '''
                if element[0] == '\'' and element[-1] == '\'':
                    element = element[1:-1]
                    
                element = element.replace('\\', '')
                
                record.append(element)
                
                if debug:
                    print(element) 

            array.append(record)
        
        return array



def read_old_full_dump(source):
    return open(source, 'r').read


